$(document).ready(function() {
	$("li.menu-login-form").hide();
	$("#menu-add-button a").attr("href", "#");
	$("#menu-login-button").click(function() {
		$("li.menu-login-form").toggle(100);
		$("#username").focus();
	});
	$("#radio-bookmark").click(function() {
		$("li#bookmark-form-item").show(100);
	});
	$("#radio-note").click(function() {
		$("li#bookmark-form-item").hide(100);
	});
	$("#menu-add-button").click(function() {
		$(".add-form").slideToggle();
		$("#url-text").focus();
	});
	$("#nav-add-form").ajaxForm({
	        // dataType identifies the expected content type of the server
			// response
	        dataType:  'xml',
	        beforeSubmit: validateAddForm,
	        // success identifies the function to invoke when the server
			// response
	        // has been received
	        success:   CallbackStatusBar
	    });
});

function changeHiddenToken(formid, newtoken) {
    //console.log($('#nav-add-form input[name="token"][type=hidden]').val(newtoken)); broken!
    var inputs = document.getElementById(formid).getElementsByTagName("input");
    for(i in inputs) {
    	if (inputs[i].type=='hidden' && inputs[i].name=="token") {
    		console.log(inputs[i].value);
    		inputs[i].value=newtoken;
    		console.log(inputs[i].value);
    	}
    }
}

function toggleAddForm() {
	$(".add-form").slideToggle();
}

function showLoader() {
	$(".toploadingbar").show();

}
function hideLoader() {
	$(".toploadingbar").hide();
}
function showAndFadeStatusBar(msg, err) {
	$(".topstatusbar").hide();
	if(err=="0") {
		$(".topstatusbar").css("background","#91f1a0");
	} else {
		$(".topstatusbar").css("background","#f19191");
	}
	$(".topstatusbar").html(msg);
    $(".topstatusbar").show(100);
    $(".topstatusbar").fadeOut(5000);
}

function validateAddForm() {
	showLoader();
	return true;
}

function CallbackStatusBar(responseXML) {
    // 'responseXML' is the XML document returned by the server; we use
    // jQuery to extract the content of the message node from the XML doc
    var message = $('statustext', responseXML).text();
    var statusnum =  $('status', responseXML).text();
    var newtoken = $('newtoken', responseXML).text();
    if(statusnum=="0") {
        toggleAddForm();
    	$("#nav-add-form").clearForm();
    } 
    changeHiddenToken("nav-add-form", newtoken);
    //$('input[name="token"][type=hidden]').attr('value', newtoken);
    showAndFadeStatusBar(message, statusnum);
    hideLoader();
    
}
